import storage from 'store'
import { authorizationApi } from '@/api/index'
const authorization = {
    namespaced: true,
    state: {
        captcha: {
            src: '',
            uuid: '',
        },
        token: storage.get('token') || '',
        userInfo: {
            name: '',
            avatar: '',
        },
        resources: [],
    },
    mutations: {
        SET_CAPTCHA(state, { src, uuid }) {
            state.captcha.src = src
            state.captcha.uuid = uuid
        },
        SET_TOKEN(state, token) {
            state.token = token
        },

        SET_USERINFO(state, { name, avatar }) {
            state.userInfo.name = name
            state.userInfo.avatar = avatar
        },

        SET_RESOURCES(state, { resourceResults }) {
            state.resources = resourceResults
        },
    },
    actions: {
        CAPTCHA({ commit }) {
            commit('SET_CAPTCHA', authorizationApi.captcha())
        },
        LOGIN({ commit }, param) {
            return new Promise((resolve, reject) => {
                authorizationApi.login(param).then(response => {
                    const { code, message, data } = response.data
                    if (code === 200) {
                        storage.set('token', data, 7 * 24 * 60 * 60 * 1000)
                        commit('SET_TOKEN', data)
                        resolve(message)
                    } else {
                        reject(message)
                    }
                }).catch(error => {
                    reject(error)
                })
            })
        },
        AUTHORIZATION({ commit }) {
            return new Promise((resolve, reject) => {
                authorizationApi.authorization().then(response => {
                    const { code, message, data } = response.data
                    if (code === 200) {
                        commit('SET_USERINFO', data)
                        commit('SET_RESOURCES', data)
                        resolve(message)
                    } else {
                        reject(message)
                    }
                }).catch(error => {
                    reject(error)
                })
            })
        },

        LOGOUT({ commit }) {
            return new Promise((resolve, reject) => {
                authorizationApi.logout().then(response => {
                    const { code, message } = response.data
                    if (code === 200) {
                        storage.remove('token')
                        commit('SET_TOKEN', '')
                        resolve(message)
                    } else {
                        reject(message)
                    }

                }).catch(error => {
                    reject(error)
                })
            })
        }
    },
}
export default authorization